﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using CommunityServer.WebServices.MediaGalleries;
using System.IO;
using System.Net;
using System.Threading;
using System.Xml;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Web;

namespace nb.development.csmediamanager
{
    public partial class Main : Form
    {
        private bool loaded;
        private Dictionary<Guid, Site> sites;
        #region Form Events
        public Main()
        {
            InitializeComponent();
            loaded = false;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            Cursor = Cursors.AppStarting;
            Width = Sites.Instance.Size.X;
            Height = Sites.Instance.Size.Y;
            menuItem5.Checked = FileShellExtension.isRegistered();
            doLoad();
            doLoadViewMode();
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void Main_Resize(object sender, EventArgs e)
        {
            Sites.Instance.Size = new Point(this.Width, this.Height);
            doFrame();
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (VistaControls.OSSupport.IsCompositionEnabled)
            {
                doFrame();
                VistaDWM.WTA_OPTIONS ops = new VistaDWM.WTA_OPTIONS();
                ops.Flags = VistaDWM.WTNCA_NODRAWCAPTION | VistaDWM.WTNCA_NODRAWICON;
                ops.Mask = VistaDWM.WTNCA_NODRAWCAPTION | VistaDWM.WTNCA_NODRAWICON;
                VistaDWM.SetWindowThemeAttribute(this.Handle, VistaDWM.WindowThemeAttributeType.WTA_NONCLIENT, ref ops, (uint)Marshal.SizeOf(typeof(VistaDWM.WTA_OPTIONS)));
                minIcon.Visible = true;
                title.Visible = true;
            }
            else
            {
                ShowIcon = true;
                topPanel.BackColor = Color.FromName("Control");
                infoPanel.Visible = false;
                minIcon.Visible = false;
                title.Visible = false;
                if (!VistaControls.OSSupport.IsVistaOrBetter)
                {
                    toolBar.Show();
                    file.Hide();
                    viewToggle.Hide();
                    mysites.Hide();
                }
            }
        }
        #endregion
        #region Form Load Helpers
        private void doFrame()
        {
            if (!VistaControls.OSSupport.IsCompositionEnabled) return;
            VistaControls.DWM.Margins m;
            if (loaded)
                m = new VistaControls.DWM.Margins(0, 0, 35, 44);
            else m = new VistaControls.DWM.Margins((Width / 2) - 80, (Width / 2) - 80, (Height / 2) - 30, (Height / 2) - 30);
            VistaControls.DWM.DWMManager.EnableGlassFrame(this, m);
            VistaControls.DWM.GlassHelper.HandleFormMovementOnGlass(this, m);
            VistaControls.DWM.GlassHelper.HandleBackgroundPainting(this, m);
        }

        private void mysites_Click(object sender, EventArgs e)
        {
            MySites o = new MySites();
            if (o.ShowDialog(this) == DialogResult.OK)
            {
                loaded = false;
                doLoad();
            }
        }

        private void toolBar_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            if (e.Button.Name == mysitesTButton.Name)
                mysites_Click(mysites, new EventArgs());
        }

        private bool canLoad()
        {
            if (Sites.Instance.Count > 0) return true;
            return false;
        }

        private void doLoad()
        {
            galleryList.Nodes.Clear();
            fileView.Items.Clear();
            if (canLoad())
            {
                doFrame();
                lblLoading.Text = "Loading...";
                sites = new Dictionary<Guid, Site>();
                foreach (Site site in Sites.Instance.Values)
                {
                    sites.Add(site.Id, site);
                    TreeNode node = new TreeNode(site.Name);
                    node.Name = site.Id.ToString();
                    MenuItem item2 = new MenuItem("Open in Browser");
                    item2.Name = node.Name + "\\o";
                    item2.Click += new EventHandler(item4_Click);
                    MenuItem item = new MenuItem("Refresh");
                    item.Name = node.Name + "\\r";
                    item.Click += new EventHandler(item2_Click);
                    item.Enabled = false;
                    item2.DefaultItem = true;
                    ContextMenu menu = new ContextMenu(new MenuItem[] { item, new MenuItem("-"), item2 });
                    node.ContextMenu = menu;
                    node.Nodes.Add("Loading...");
                    if (!site.Collapsed)
                        node.Expand();
                    galleryList.Nodes.Add(node);
                    GalleryWorker gw = new GalleryWorker(site.Id);
                    gw.Completed += new GalleryWorkerCompleted(gw_Completed);
                    Thread t = new Thread(new ThreadStart(gw.Run));
                    t.Start();
                }
                LoadDone();
            }
            else
            {
                doFrame();
                this.Cursor = Cursors.Default;
                lblLoading.Text = "Enter Your Sites";
            }
        }

        private void LoadDone()
        {
            loaded = true;
            doFrame();
            lblLoading.Hide();
            if (VistaControls.OSSupport.IsCompositionEnabled)
                infoPanel.Show();
            hSplit.Show();
            Cursor = Cursors.Default;
        }

        private void doLoadViewMode()
        {
            switch (Sites.Instance.ViewMode)
            {
                case View.LargeIcon:
                    fileView.LargeImageList = imageList1;
                    viewLarge.Checked = true;
                    viewSmall.Checked = false;
                    viewTiles.Checked = false;
                    viewList.Checked = false;
                    fileView.View = View.LargeIcon;
                    break;
                case View.SmallIcon:
                    viewLarge.Checked = false;
                    viewSmall.Checked = true;
                    viewTiles.Checked = false;
                    viewList.Checked = false;
                    fileView.View = View.SmallIcon;
                    break;
                case View.Tile:
                    fileView.LargeImageList = imageList4;
                    viewLarge.Checked = false;
                    viewSmall.Checked = false;
                    viewTiles.Checked = true;
                    viewList.Checked = false;
                    fileView.View = View.Tile;
                    break;
                case View.List:
                    viewLarge.Checked = false;
                    viewSmall.Checked = false;
                    viewTiles.Checked = false;
                    viewList.Checked = true;
                    fileView.View = View.List;
                    break;
            }
        }

        #endregion
        #region GalleryList Load Helper
        void gw_Completed(Guid siteid, Dictionary<int, MediaGallery> galleries, Dictionary<int, MediaGalleryGroup> groups)
        {
            if (galleryList.InvokeRequired)
            {
                GalleryWorkerCompleted done = new GalleryWorkerCompleted(gw_Completed);
                try { galleryList.Invoke(done, siteid, galleries, groups); }
                catch { }
            }
            else
            {
                try
                {
                    TreeNode root = galleryList.Nodes[siteid.ToString()];
                    root.ContextMenu.MenuItems[1].Enabled = true;
                    root.Nodes.Clear();
                    sites[siteid].Galleries = galleries;
                    sites[siteid].Groups = groups;
                    foreach (MediaGallery g in galleries.Values)
                    {
                        TreeNode n = null;
                        if (root.Nodes.Find(siteid.ToString() + "\\" + g.MediaGalleryGroupId.ToString(), false).Length > 0)
                            n = root.Nodes.Find(siteid.ToString() + "\\" + g.MediaGalleryGroupId.ToString(), false)[0];
                        if (n != null) addGallery(g, n);
                        else
                        {
                            TreeNode node = new TreeNode(HttpUtility.HtmlDecode(groups[g.MediaGalleryGroupId].Name));
                            node.ToolTipText = HttpUtility.HtmlDecode(groups[g.MediaGalleryGroupId].Description);
                            node.Name = siteid.ToString() + "\\" + g.MediaGalleryGroupId.ToString();
                            addGallery(g, node);
                            root.Nodes.Add(node);
                        }
                    }                    
                }
                catch (Exception e) { MessageBox.Show("Error: " + e.Message, "Error Loading Galleries", MessageBoxButtons.OK, MessageBoxIcon.Error); }
                this.LoadDone();
            }
        }

        private void addGallery(MediaGallery g, TreeNode node)
        {
            TreeNode n = new TreeNode(HttpUtility.HtmlDecode(g.Name));
            n.Name = node.Name + "\\" + g.Id;
            MenuItem item = new MenuItem("Add Post Here");
            item.Name = n.Name + "\\a";
            item.Click += new EventHandler(item_Click);
            MenuItem item2 = new MenuItem("Refresh Tags");
            item2.Name = n.Name + "\\r";
            item2.Click += new EventHandler(item2_Click);
            item2.Enabled = false;
            MenuItem item4 = new MenuItem("Open in Browser");
            item4.Name = n.Name + "\\o";
            item4.Click += new EventHandler(item4_Click);
            MenuItem item5 = new MenuItem("&Properties");
            item5.DefaultItem = true;
            item5.Name = n.Name + "\\p";
            item5.Click += new EventHandler(item5_Click);
            ContextMenu menu = new ContextMenu(new MenuItem[] { item, item2, item5, new MenuItem("-"), item4 });
            n.ContextMenu = menu;
            n.Collapse();
            n.ToolTipText = g.Description;
            n.Nodes.Add("Loading...");
            node.Nodes.Add(n);
            node.Expand();
        }
        
        void item5_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            string[] s = item.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            Guid siteid = new Guid(s[0]);
            int galleryid = int.Parse(s[2]);
            GalleryProperties prop = new GalleryProperties(sites[siteid].Galleries[galleryid], siteid);
            prop.Saved += new Saved(gprop_Saved);
            prop.Show(this);
        }

        void gprop_Saved(MediaGallery gallery, Guid siteid)
        {
            TreeNode node = galleryList.Nodes.Find(siteid.ToString() + '\\' + gallery.MediaGalleryGroupId + '\\' + gallery.Id, true)[0];
            sites[siteid].Galleries[gallery.Id] = gallery;
            bool t = false;
            if (node == galleryList.SelectedNode) t = true;
            node.Text = gallery.Name;
            if (t) galleryList_AfterSelect(galleryList, new TreeViewEventArgs(node));
        }


        void item4_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            string[] s = item.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            ProcessStartInfo sInfo;
            if (s.Length == 2) sInfo = new ProcessStartInfo(sites[new Guid(s[0])].Url);
            else sInfo = new ProcessStartInfo(sites[new Guid(s[0])].Galleries[int.Parse(s[2])].Url);
            try { Process.Start(sInfo); }
            catch { }
        }

        void item2_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            string[] s = item.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            TreeNode t;
            if (s.Length == 2) t = galleryList.Nodes.Find(s[0], true)[0];
            else t = galleryList.Nodes.Find(s[0] + '\\' + s[1] + '\\' + s[2], true)[0];
            t.Collapse();
            t.Nodes.Clear();
            t.Nodes.Add("Loading...");
            t.Expand();
            if (s.Length == 2)
            {
                GalleryWorker gw = new GalleryWorker(new Guid(s[0]));
                gw.Completed += new GalleryWorkerCompleted(gw_Completed);
                Thread thr = new Thread(new ThreadStart(gw.Run));
                thr.Start();
            }
        }

        void item_Click(object sender, EventArgs e)
        {
            MenuItem item = sender as MenuItem;
            string[] s = item.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            Guid siteid = new Guid(s[0]);
            int galleryid = int.Parse(s[2]);
            string tag = string.Empty;
            if (s.Length == 5)
                tag = galleryList.Nodes.Find(s[0] + "\\" + s[1] + "\\" + s[2] + "\\" + s[3], true)[0].Text;
            NewPost post = new NewPost(sites[siteid].Galleries[galleryid], siteid, tag);
            post.Show(this);
            post.FormClosed += new FormClosedEventHandler(post_FormClosed);
        }

        private TreeNode FindTreeNode(int x, int y)
        {
            TreeNode aNode = galleryList.Nodes[0];
            Point pt = new Point(x, y);
            pt = PointToClient(pt);
            while (aNode != null)
            {
                if (aNode.Bounds.Contains(pt)) return aNode;
                aNode = aNode.NextVisibleNode;
            }
            return null;
        }
        #endregion
        #region fileView Load Helpers
        void worker_Completed(Image image, MediaGalleryPost post, string path)
        {
            if (fileView.InvokeRequired)
            {
                ImageWorkerCompleted done = new ImageWorkerCompleted(worker_Completed);
                try { fileView.Invoke(done, image, post, path); }
                catch { }
            }
            else
            {
                if (galleryList.SelectedNode.Name == path || galleryList.SelectedNode.Parent.Name + "\\" + galleryList.SelectedNode.Text.Replace("\\", "") == path)
                {
                    imageList1.Images.Add("post" + post.Id.ToString(), image);
                    imageList3.Images.Add("post" + post.Id.ToString(), image);
                    imageList4.Images.Add("post" + post.Id.ToString(), image);
                    fileView.Items["post" + post.Id.ToString()].ImageKey = "post" + post.Id.ToString();
                }
            }
        }

        void pw_PostAdded(MediaGalleryPost post, string path)
        {
            if (galleryList.InvokeRequired)
            {
                PostAdded done = new PostAdded(pw_PostAdded);
                try { galleryList.Invoke(done, post, path); }
                catch { }
            }
            else
            {
                if (galleryList.SelectedNode.Name == path || galleryList.SelectedNode.Parent.Name + "\\" + galleryList.SelectedNode.Text.Replace("\\", "") == path)
                {
                    ListViewItem item = new ListViewItem(post.Title);
                    item.Name = "post" + post.Id;
                    string s = post.Attachment.Endpoint.Substring(post.Attachment.Endpoint.LastIndexOf('.')).ToLower();
                    if (s.Length > 5)
                    {
                        if (s.ToCharArray()[s.Length - 4] == '_') s = '.' + s.Substring(s.Length - 3);
                        else if (s.ToCharArray()[s.Length - 5] == '_') s = '.' + s.Substring(s.Length - 4);
                    }
                    if (!imageList1.Images.ContainsKey(s))
                    {
                        Bitmap b = new Bitmap(128, 128);
                        Graphics g = Graphics.FromImage(b);
                        g.Clear(Color.Transparent);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        Icon i = IconHelper.ExtractIconForExtension("a" + s, true);
                        int left = (128 - i.Width) / 2;
                        int top = (128 - i.Height) / 2;
                        g.DrawIconUnstretched(i, new Rectangle(left, top, i.Width, i.Height));
                        g.Flush();
                        imageList1.Images.Add(s, b);
                        imageList3.Images.Add(s, IconHelper.ExtractIconForExtension(s, false));
                        imageList4.Images.Add(s, IconHelper.ExtractIconForExtension(s, true));
                    }
                    item.ImageKey = s;
                    if (s == ".png" || s == ".jpg" || s == ".jpeg" || s == ".gif" || s == ".bmp")
                    {
                        ImageWorker worker = new ImageWorker(post, path);
                        worker.Completed += new ImageWorkerCompleted(worker_Completed);
                        Thread t = new Thread(new ThreadStart(worker.Run));
                        t.Start();
                    }
                    fileView.Items.Add(item);
                    sites[new Guid(path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)[0])].Posts.Add(post.Id, post);
                }
            }
        }
        #endregion
        #region GalleryList Events
        private void galleryList_AfterSelect(object sender, TreeViewEventArgs e)
        {
            fileView.SelectedIndices.Clear();
            fileView.SelectedItems.Clear();
            fileView.Items.Clear();
            string[] paths = e.Node.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (paths.Length < 3) { fileView.ContextMenu = null; return; }
            lblLoading.Show();
            this.Cursor = Cursors.AppStarting;
            fileView.ContextMenu = listContext;
            contextNew.Enabled = true;
            contextDelete.Enabled = false;
            contextProperties.Enabled = false;
            contextPublished.Visible = false;
            contextSpacer.Visible = false;
            fileView.SelectedItems.Clear();
            fileView.SelectedIndices.Clear();
            fileView.Items.Clear();
            imageList1.Images.Clear();
            imageList3.Images.Clear();
            imageList4.Images.Clear();
            sites[new Guid(paths[0])].Posts = new Dictionary<int, MediaGalleryPost>();
            PostWorker pw;
            if (paths.Length == 4)
                pw = new PostWorker(paths[0] + "\\" + paths[1] + "\\" + paths[2] + "\\" + e.Node.Text.Replace("\\", ""), sites[new Guid(paths[0])]);
            else pw = new PostWorker(e.Node.Name, sites[new Guid(paths[0])]);
            pw.Completed += new PostWorkerCompleted(pw_Completed);
            pw.PostAdded += new PostAdded(pw_PostAdded);
            Thread t = new Thread(new ThreadStart(pw.Run));
            t.Start();
        }

        void pw_Completed()
        {
            if (lblLoading.InvokeRequired)
            {
                PostWorkerCompleted done = new PostWorkerCompleted(pw_Completed);
                try { galleryList.Invoke(done); }
                catch { }
            }
            else
            {
                lblLoading.Hide();
                this.Cursor = Cursors.Default;
            }
        }

        private void galleryList_AfterExpand(object sender, TreeViewEventArgs e)
        {
            string[] path = e.Node.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

            if (path.Length == 3 && e.Node.Nodes[0].Text == "Loading...")
            {
                galleryList.Cursor = Cursors.AppStarting;
                TagWorker worker = new TagWorker(e.Node.Name, sites[new Guid(path[0])]);
                worker.Completed += new TagWorkerCompleted(tagworker_Completed);
                Thread t = new Thread(new ThreadStart(worker.Run));
                t.Start();
            }
            else if (path.Length == 1) Sites.Instance[new Guid(path[0])].Collapsed = !e.Node.IsExpanded;
        }


        private void galleryList_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            string[] path = e.Node.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            if (path.Length == 1) Sites.Instance[new Guid(path[0])].Collapsed = !e.Node.IsExpanded;
        }

        void tagworker_Completed(List<string> tags, string path)
        {
            if (galleryList.InvokeRequired)
            {
                TagWorkerCompleted done = new TagWorkerCompleted(tagworker_Completed);
                try { galleryList.Invoke(done, tags, path); }
                catch { }
            }
            else
            {
                TreeNode n = galleryList.Nodes.Find(path, true)[0];
                n.Nodes.Clear();
                foreach (string s in tags)
                {
                    MenuItem item = new MenuItem("Add Post Here");
                    item.Name = n.Name + "\\" + s.Replace(" ", "").ToLower().Trim() + "\\a";
                    item.Click += new EventHandler(item_Click);
                    ContextMenu menu = new ContextMenu(new MenuItem[] { item });
                    TreeNode node = new TreeNode();
                    node.Name = n.Name + "\\" + s.Replace(" ", "").ToLower().Trim();
                    node.Text = s;
                    node.ContextMenu = menu;
                    n.Nodes.Add(node);
                }
                n.ContextMenu.MenuItems[1].Enabled = true;
                galleryList.Cursor = Cursors.Default;
            }
        }

        private void galleryList_DragOver(object sender, DragEventArgs e)
        {
            TreeNode node = FindTreeNode(e.X, e.Y - 60);
            if (node != null)
            {
                string[] path = node.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                    if (path.Length > 2)
                        e.Effect = DragDropEffects.Copy;
                    else e.Effect = DragDropEffects.None;
                else
                {
                    string[] path2 = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    if (path[0] == path2[0])
                    {
                        if (path.Length == 3)
                            e.Effect = DragDropEffects.Move;
                        else if (path.Length == 4)
                            e.Effect = DragDropEffects.Copy;
                        else e.Effect = DragDropEffects.None;
                    }
                    else e.Effect = DragDropEffects.None;
                }
            }
            else e.Effect = DragDropEffects.None;
        }

        private void galleryList_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Effect == DragDropEffects.Copy || e.Effect == DragDropEffects.Move)
            {
                hSplit.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                TreeNode node = FindTreeNode(e.X, e.Y - 60);
                string[] path = node.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    uploading.Show();
                    uploadProgs.Value = 0;
                    Array a = e.Data.GetData(DataFormats.FileDrop) as Array;
                    uploadProgs.Maximum = a.Length;
                    List<FileInfo> files = new List<FileInfo>();
                    for (int x = 0; x < a.Length; x++)
                        files.Add(new FileInfo(a.GetValue(x).ToString()));
                    Uploader u = new Uploader(files, new Guid(path[0]), int.Parse(path[2]), "");
                    u.UploadCompleded += new UploadCompleted(u_UploadCompleded);
                    u.UploadedPost += new UploadedPost(u_UploadedPost);
                    Thread t = new Thread(new ThreadStart(u.UploadDirectory));
                    t.Start();
                }
                else
                {
                    lblLoading.Show();
                    string[] path2 = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    List<MediaGalleryPost> ps = new List<MediaGalleryPost>();
                    foreach (ListViewItem i in fileView.SelectedItems)
                        ps.Add(sites[new Guid(path2[0])].Posts[int.Parse(i.Name.Remove(0, 4))]);
                    foreach (MediaGalleryPost post in ps)
                    {
                        if (post.MediaGalleryId.Value != int.Parse(path[2]))
                            post.MediaGalleryId = int.Parse(path[2]);
                        if (e.Effect == DragDropEffects.Copy)
                            if (!post.Keywords.Contains(node.Text))
                                post.Keywords.Add(node.Text);
                    }
                    Updater u = new Updater(ps, new Guid(path2[0]));
                    u.UpdateCompleded += new UploadCompleted(u_UpdateCompleded);
                    Thread t = new Thread(new ThreadStart(u.Update));
                    t.Start();
                }
            }

        }

        void u_UploadedPost(int index, int count)
        {
            if (this.InvokeRequired)
            {
                UploadedPost done = new UploadedPost(u_UploadedPost);
                try { this.Invoke(done, index, count); }
                catch { }
            }
            else
            {
                uploadProgs.Value = index;
                uploadProgs.Maximum = count;
            }
        }

        void u_UploadCompleded()
        {
            if (this.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u_UploadCompleded);
                try { this.Invoke(done); }
                catch { }
            }
            else
            {
                uploading.Hide();
                uploadProgs.Value = 0;
                u_UpdateCompleded();
            }
        }

        #endregion
        #region fileView Events
        private void fileView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (fileView.SelectedItems.Count == 1)
            {
                string[] path = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                MediaGalleryPost p = sites[new Guid(path[0])].Posts[int.Parse(fileView.SelectedItems[0].Name.Replace("post", ""))];
                itemPublished.Text = "Published: " + p.Date.Value.ToShortDateString() + " " + p.Date.Value.ToShortTimeString();
                if (p.Keywords.Count > 0)
                {
                    itemTags.Text = "Tags: ";
                    List<string> tags = new List<string>();
                    foreach (string s in p.Keywords)
                        tags.Add(s);

                    itemTags.Text += string.Join(", ", tags.ToArray());
                }
                else itemTags.Text = "No Tags";
                itemUrl.Text = "Url: " + p.Url;
                contextNew.Enabled = true;
                contextTag.Enabled = true;
                contextDelete.Enabled = true;
                contextProperties.Enabled = true;
                contextPublished.Visible = true;
                contextPublished.Checked = p.IsPublished.Value;
                contextSpacer.Visible = true;
            }
            else if (fileView.SelectedItems.Count > 1)
            {
                itemPublished.Text = fileView.SelectedItems.Count + " Items Selected";
                itemTags.Text = "";
                itemUrl.Text = "";
                contextNew.Enabled = true;
                contextTag.Enabled = true;
                contextDelete.Enabled = true;
                contextProperties.Enabled = false;
                contextPublished.Visible = true;
                contextPublished.Checked = false;
                contextSpacer.Visible = true;
            }
            else
            {
                itemPublished.Text = "";
                itemTags.Text = "";
                itemUrl.Text = "";
                contextNew.Enabled = true;
                contextDelete.Enabled = false;
                contextTag.Enabled = false;
                contextProperties.Enabled = false;
                contextPublished.Visible = false;
                contextPublished.Checked = false;
                contextSpacer.Visible = false;
            }
        }
        private void fileView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                contextDelete_Click(sender, new EventArgs());
        }

        private void contextNew_Click(object sender, EventArgs e)
        {
            string[] path = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            int galleryid = int.Parse(path[2]);
            Guid siteid = new Guid(path[0]);
            string tag = string.Empty;
            if (path.Length == 4)
                tag = galleryList.SelectedNode.Text;
            NewPost post = new NewPost(sites[siteid].Galleries[galleryid], siteid, tag);
            post.Show(this);
            post.FormClosed += new FormClosedEventHandler(post_FormClosed);
        }

        private void contextTag_Click(object sender, EventArgs e)
        {
            string[] paths = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            List<MediaGalleryPost> ps = new List<MediaGalleryPost>();
            for (int x = 0; x < fileView.SelectedIndices.Count; x++)
                ps.Add(sites[new Guid(paths[0])].Posts[int.Parse(fileView.SelectedItems[x].Name.Remove(0, 4))]);
            TagBox tb = new TagBox(ps, new Guid(paths[0]));
            tb.Show(this);
        }

        void post_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (((NewPost)sender).DialogResult == DialogResult.OK)
                galleryList_AfterSelect(galleryList, new TreeViewEventArgs(galleryList.SelectedNode));
        }

        private void fileView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                contextProperties_Click(contextProperties, new EventArgs());
        }

        private void contextProperties_Click(object sender, EventArgs e)
        {
            string[] path = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
            ItemProperties prop = new ItemProperties(sites[new Guid(path[0])].Posts[int.Parse(fileView.SelectedItems[0].Name.Remove(0, 4))], new Guid(path[0]));
            prop.Saved += new EventHandler(prop_Saved);
            prop.Show(this);
        }

        void prop_Saved(object sender, EventArgs e)
        {
            galleryList_AfterSelect(galleryList, new TreeViewEventArgs(galleryList.SelectedNode));
        }

        private void fileView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop("", DragDropEffects.Copy | DragDropEffects.Move);
        }

        private void fileView_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                if (galleryList.SelectedNode == null) e.Effect = DragDropEffects.None;
                else
                {
                    string[] path = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                    if (path.Length > 2) e.Effect = DragDropEffects.Copy;
                    else e.Effect = DragDropEffects.None;
                }
            }
            else
                e.Effect = DragDropEffects.None;
        }

        private void fileView_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Effect == DragDropEffects.Copy && e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                hSplit.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                string[] path = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                uploading.Show();
                uploadProgs.Value = 0;
                Array a = e.Data.GetData(DataFormats.FileDrop) as Array;
                uploadProgs.Maximum = a.Length;
                List<FileInfo> files = new List<FileInfo>();
                for (int x = 0; x < a.Length; x++)
                    files.Add(new FileInfo(a.GetValue(x).ToString()));
                Uploader u = null;
                if (path.Length == 4) u = new Uploader(files, new Guid(path[0]), int.Parse(path[2]), path[3]);
                else u = new Uploader(files, new Guid(path[0]), int.Parse(path[2]), "");
                u.UploadCompleded += new UploadCompleted(u_UploadCompleded);
                u.UploadedPost += new UploadedPost(u_UploadedPost);
                Thread t = new Thread(new ThreadStart(u.UploadDirectory));
                t.Start();
            }
        }

        #endregion
        #region View Drop Down

        private void viewToggle_Click(object sender, EventArgs e)
        {
            viewContext.Show(viewToggle, new Point(viewToggle.Width, viewToggle.Height), LeftRightAlignment.Left);
        }

        private void viewLarge_Click(object sender, EventArgs e)
        {
            Sites.Instance.ViewMode = View.LargeIcon;
            doLoadViewMode();
        }

        private void viewSmall_Click(object sender, EventArgs e)
        {
            Sites.Instance.ViewMode = View.SmallIcon;
            doLoadViewMode();
        }

        private void viewList_Click(object sender, EventArgs e)
        {
            Sites.Instance.ViewMode = View.List;
            doLoadViewMode();
        }

        private void viewTiles_Click(object sender, EventArgs e)
        {
            Sites.Instance.ViewMode = View.Tile;
            doLoadViewMode();
        }
        #endregion
        #region File Drop Down

        private void file_Click(object sender, EventArgs e)
        {
            fileContext.Show(file, new Point(0, file.Height), LeftRightAlignment.Right);
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
            Application.Exit();
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog(this);
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            if (!menuItem5.Checked)
            {
                FileShellExtension.Register();
                MessageBox.Show("The shell extension was registered.", "Extension Registered");
            }
            else
            {
                FileShellExtension.Unregister();
                MessageBox.Show("The shell extension was removed.", "Extension Removed");
            }
            menuItem5.Checked = FileShellExtension.isRegistered();
        }

        #endregion
        #region Delete Posts

        private void contextDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete these Media Posts?", "Delete Question?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                string[] paths = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                deleting.Show();
                deleteProgs.Value = 0;
                deleteProgs.Maximum = fileView.SelectedIndices.Count;
                List<int> ids = new List<int>();
                for (int x = 0; x < fileView.SelectedIndices.Count; x++)
                    ids.Add(int.Parse(fileView.SelectedItems[x].Name.Remove(0, 4)));
                Deleter d = new Deleter(ids, new Guid(paths[0]));
                Cursor = Cursors.WaitCursor;
                hSplit.Enabled = false;
                d.Deleted += new DeletedPost(d_Deleted);
                Thread t = new Thread(new ThreadStart(d.Run));
                t.Start();
            }
        }

        void d_Deleted(int index, int count, Exception e)
        {
            if (deleteProgs.InvokeRequired)
            {
                DeletedPost done = new DeletedPost(d_Deleted);
                try { deleteProgs.Invoke(done, index, count, e); }
                catch { }
            }
            else
            {
                deleteProgs.Value = index;
                if (e != null) deleteProgs.ProgressState = VistaControls.ProgressBar.States.Paused;
                if (index == count)
                {
                    galleryList_AfterSelect(galleryList, new TreeViewEventArgs(galleryList.SelectedNode));
                    deleting.Hide();
                    hSplit.Enabled = true;
                    Cursor = Cursors.Default;
                }
            }
        }

        #endregion
        #region Publish/UnPublish Posts
        private void contextPublished_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to change the published status of these Media Posts?", "Publish Question?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                string[] paths = galleryList.SelectedNode.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                lblLoading.Show();
                this.Cursor = Cursors.WaitCursor;
                hSplit.Enabled = false;
                List<MediaGalleryPost> ps = new List<MediaGalleryPost>();
                for (int x = 0; x < fileView.SelectedIndices.Count; x++)
                    ps.Add(sites[new Guid(paths[0])].Posts[int.Parse(fileView.SelectedItems[x].Name.Remove(0, 4))]);
                foreach (MediaGalleryPost post in ps) post.IsPublished = !post.IsPublished.Value;
                Updater u = new Updater(ps, new Guid(paths[0]));
                u.UpdateCompleded += new UploadCompleted(u_UpdateCompleded);
                Thread t = new Thread(new ThreadStart(u.Update));
                t.Start();
            }

        }

        void u_UpdateCompleded()
        {
            if (this.InvokeRequired)
            {
                UploadCompleted done = new UploadCompleted(u_UpdateCompleded);
                try { this.Invoke(done); }
                catch { }
            }
            else
            {
                hSplit.Enabled = true;
                this.Cursor = Cursors.Default;
                lblLoading.Hide();
                galleryList_AfterSelect(galleryList, new TreeViewEventArgs(galleryList.SelectedNode));
            }
        }
        #endregion
    }
}
